<template>
  <div class="circle-detail">
    <div class="circle-itme">
      <h3>朋友圈内容</h3>
      <div class="circle-content-box scroll">
        <div class="circle-content" v-html="decodeCircleContent(circleData.remarks)"></div>
        <!-- 任务时间 -->
        <p class="text-content">
          {{ new Date(circleData.execute_time).toLocaleString() }}
        </p>
        <div class="like-list">
          <i class="fa fa-heart-o" aria-hidden="true"></i>
          <span v-for="(liker, index) in likes" :key="index" v-text="liker.nickname"></span>
        </div>
      </div>

      <h3>添加评论</h3>
      <div class="comments-box">
        <!-- 选择账号 -->
        <el-select
          v-if="wechats.length > 0"
          v-model="wechats2comment"
          placeholder="全部个人号"
          multiple
          collapse-tags
          clearable
        >
          <el-option
            v-for="(wechat, index4) in wechats"
            :key="index4"
            :label="wechat.wechatnick"
            :value="wechat.wechatid"
          />
        </el-select>

        <!-- 要提交的评论 -->
        <div class="comments-to-send scroll">
          <div v-for="(comment, index2) in comments2send" :key="'comment' + index2" class="comment-content">
            <p class="ellipsis" :title="comment" v-text="comment.content"></p>
            <i class="el-icon-delete" @click="removeComment(index2, comment)"></i>
          </div>
        </div>

        <!-- 前缀 -->
        <div class="prefix-box">
          <p style="margin-right: 10px">前缀</p>
          <el-radio v-model="commentPrefix2" label="同学：">同学：</el-radio>
          <el-radio v-model="commentPrefix2" label="楼主：">楼主：</el-radio>
          <el-radio v-model="commentPrefix2" label="网友：">网友：</el-radio>
          <el-radio v-model="commentPrefix2" label="空">空</el-radio>
        </div>
      </div>

      <el-button size="mini" class="submit-comment-btn" type="primary" icon="el-icon-position" @click="submitComments">
        提 交
      </el-button>
    </div>

    <div class="comment-list">
      <h3>
        评论列表
        <el-button style="margin-left: 10px" icon="el-icon-refresh" type="text" @click="freshCommentsList"></el-button>
      </h3>

      <div class="comment-data">
        <!-- 数据展示 -->
        <ul class="comment-ul scroll">
          <li v-for="(comment, index3) in commentsList" :key="'li' + index3" class="comment-item">
            <div class="comment-item-cotent">
              <el-checkbox
                v-model="commentsCheckedMap[comment.id]"
                style="margin-right: 10px"
                @change="checkComment($event, comment)"
              ></el-checkbox>
              <el-avatar :size="30" style="margin-right: 10px; min-width: 30px" :src="comment.avatar">
                <i class="fa fa-picture-o" aria-hidden="true" title="头像miss"></i>
              </el-avatar>
              <div>
                <el-row type="flex">
                  <p style="margin-right: 10px; padding: 5px" v-text="comment.fromname"></p>
                  <p style="margin-right: 10px; padding: 5px">{{ new Date(comment.publishtime).toLocaleString() }}</p>
                  <p v-if="comment.flag" style="padding: 5px; color: red">已跟评</p>
                  <p v-else style="padding: 5px">未跟评</p>
                </el-row>
                <p style="padding: 5px" v-text="comment.comment"></p>
              </div>
            </div>
            <div class="comment-item-btns">
              <el-button size="mini" type="danger" @click="deleteComment(comment)">删除</el-button>
              <el-button type="primary" size="mini" @click="replyComment(comment)">回复</el-button>
              <el-button type="primary" size="mini" @click="showCommentPrefix($event, comment)">跟评</el-button>
            </div>
          </li>
        </ul>

        <!-- 分页 -->
        <Pagination
          v-show="total > 0"
          style="background: #f9fafc"
          :total="total"
          :page.sync="pageNo"
          :limit.sync="pageSize"
          @pagination="getCommentsListById"
        />

        <!-- 评论区域 -->
        <el-input
          v-model="currentComment"
          class="comment-input-area"
          type="textarea"
          :rows="4"
          clearable
          resize="none"
          placeholder="添加评论"
          maxlength="500"
        ></el-input>

        <el-button size="mini" class="add-comment-btn" type="primary" icon="el-icon-position" @click="addComment">
          添加
        </el-button>
      </div>
    </div>

    <div v-if="showPrefix" class="show-model2" @click="hidePrefix"></div>
    <div v-show="showPrefix" id="followComment2">
      <div class="follow-comment2">
        <el-radio v-model="commentPrefix2" label="同学：">同学：</el-radio>
        <el-radio v-model="commentPrefix2" label="楼主：">楼主：</el-radio>
        <el-radio v-model="commentPrefix2" label="网友：">网友：</el-radio>
        <el-radio v-model="commentPrefix2" label="空">空</el-radio>
        <el-button type="primary" size="mini" @click="replyCommentByPrepend2">确定</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'

import Pagination from '@/components/Pagination' // 基于el-pagination组件封装的分页主键
import { CircleCommentReplyTask } from '@/api/webSocketApi'
import {
  queryCommentsById,
  queryWechatsById,
  deleteCircleComment,
  followCircleComments,
  followMoreComment,
  queryCircleLike
} from '@/api/front/circle'

export default {
  name: 'CircleDetail',
  components: { Pagination },
  data() {
    return {
      currentComment: '',
      comments2send: [],
      wechats: [], // 该任务下的微信
      wechats2comment: [], // 要评论的微信id
      likes: [], // 点赞信息

      showPrefix: false, // 展示前缀
      commentPrefix2: '空', // 评论前缀
      followCommentContent: {}, // 跟评的内容

      listLoading: true, // 正在获取数据
      commentsList: [], // 表格中的数据
      commentsCheckedMap: {}, // 评论的选中状态

      total: 0, // 数据总数
      pageNo: 1, // 页
      pageSize: 20 // 页面大小
    }
  },
  computed: {
    ...mapGetters({
      currentUser: 'currentUser',
      circleData: 'circleManager/circleData'
    })
    // dataId() {
    //   return this.circleData.id
    // }
  },
  watch: {
    // dataId() {
    //   this.showPrefix = false
    //   // 先重置数据
    //   this.wechats = []
    //   this.commentsList = []
    //   this.likes = []
    //   this.total = 0
    //   // 获取所有的账号信息
    //   this.getWechatsList()
    //   // 获取评论列表
    //   this.getCommentsListById()
    //   // 获取点赞信息
    //   this.getLikes()
    //   this.comments2send = []
    // }
  },
  created() {
    if (this.circleData.id) {
      // 获取所有的账号信息
      this.getWechatsList()
      // 获取评论列表
      this.getCommentsListById()
      // 获取点赞信息
      this.getLikes()
      this.comments2send = []
    }
  },
  destroyed() {
    this.showPrefix = false
    this.$store.commit('circleManager/SET_CIRCLE_DATA', {})
  },

  methods: {
    // 解析朋友圈内容
    decodeCircleContent(content) {
      try {
        const jContent = JSON.parse(content)
        const { circleType, textContent, attachtContent } = jContent
        let AttachContent = []
        if (attachtContent) {
          AttachContent = attachtContent.split(',')
        }
        if (circleType === 'text') {
          return `<p style="line-height: 30px;">${textContent}</p>`
        } else if (circleType === 'picture') {
          let imgStr = ''
          for (const ac of AttachContent) {
            imgStr = imgStr + `<img style="width:33%;padding:5px;" src="${ac}" />`
          }
          return `<p style="line-height: 30px;">${textContent}</p>
              <div style="display:flex;flex-wrap:wrap;">${imgStr}</div>
              `
        } else if (circleType === 'video') {
          return `<p style="line-height: 30px;">${textContent}</p>
            <video style="padding:5px;" src="${attachtContent}" controls></video>
            `
        } else {
          // 链接
          const title = AttachContent[1]
          const imgUrl = AttachContent[2]
          return `<p style="line-height: 30px;">${textContent}</p>
            <div style="display:flex;align-items:center;">
            <img style="width:30%;margin-right:5px;" src="${imgUrl}" />
            <span>${title}</span>
            </div>
            `
        }
      } catch (error) {
        return content
      }
    },
    // 获取评论列表
    getCommentsListById() {
      queryCommentsById(this.circleData.id, this.pageNo, this.pageSize)
        .then((res) => {
          this.commentsList = res?.data?.rows || []
          this.commentsList.forEach((x) => {
            this.commentsCheckedMap[x.id] = false
          })
          this.total = res?.data?.records || 0
          this.listLoading = false
        })
        .catch((err) => {
          console.log(err)
        })
    },
    // 获取该任务的微信列表
    getWechatsList() {
      queryWechatsById(this.circleData.id).then((res) => {
        this.wechats = res?.data || []
        // 默认全选
        this.wechats2comment = this.wechats.map((x) => {
          return x.wechatid
        })
      })
    },
    getLikes() {
      queryCircleLike(this.circleData.id).then((res) => {
        this.likes = res?.data || []
      })
    },
    // 刷新评论列表
    freshCommentsList() {
      this.pageNo = 1
      this.getCommentsListById()
    },
    // 删除评论
    deleteComment(comment) {
      const { wechatid, fromwechatid, id } = comment
      if (fromwechatid && fromwechatid !== wechatid) {
        this.$message.warning('不能删除别人的评论！')
        return
      }

      this.$confirm('确认删除该评论 ?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteCircleComment(id).then((res) => {
            if (res.code === 0) {
              this.$message.success('任务已经下发，请稍后刷新数据！')
            }
          })
        })
        .catch(() => {})
    },
    // 回复
    replyComment(comment) {
      const { circle_wechatid, fromwechatid, circleid, commentid } = comment
      if (circle_wechatid === fromwechatid) {
        this.$message.warning('不能回复自己的评论！')
        return
      }
      this.$prompt('请输入评论内容', '评论', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /\S{1,500}/,
        inputErrorMessage: '评论字数1-500'
      })
        .then(({ value }) => {
          CircleCommentReplyTask(circle_wechatid, circleid, value, fromwechatid, commentid)
          this.$message.success('任务已经下发，请稍后刷新数据！')
        })
        .catch(() => {})
    },
    // 展示跟评
    showCommentPrefix(e, row) {
      const wH = window.innerHeight
      const wW = window.innerWidth
      const left = e.pageX - wW / 10 - 440 + 30
      const top = e.pageY - wH / 10 + 30
      this.followCommentContent = row
      const fcDom = document.getElementById('followComment2')
      if (fcDom) {
        fcDom.style.top = top + 'px'
        fcDom.style.left = left + 'px'
      }
      this.showPrefix = true
    },
    hidePrefix() {
      this.showPrefix = false
    },
    // 跟评
    replyCommentByPrepend2() {
      const { circle_wechatid, circleid, comment, id } = this.followCommentContent
      let commentConntent = comment
      if (this.commentPrefix2 !== '空') {
        commentConntent = this.commentPrefix2 + comment
      }
      followCircleComments(circle_wechatid, circleid, commentConntent, id).then((res) => {
        if (res.code === 0) {
          this.$message.success('跟评任务已经下发，请稍后刷新数据！')
        }
      })
      this.showPrefix = false
    },
    // 选中评论列表中的评论，添加或移除待评区
    checkComment(e, commentTtem) {
      const { comment, id } = commentTtem
      if (e) {
        this.comments2send.push({ id: id, content: comment })
      } else {
        this.comments2send = this.comments2send.filter((x) => {
          return x.id !== id
        })
      }
    },
    // 添加评论
    addComment() {
      if (this.currentComment) {
        this.comments2send.push({ id: 'myadd' + this.currentComment, content: this.currentComment })
        this.currentComment = ''
      }
    },
    // 移除评论
    removeComment(index, comment) {
      this.comments2send.splice(index, 1)
      if (comment.id !== comment.content) {
        this.commentsCheckedMap[comment.id] = false
        this.$forceUpdate()
      }
    },
    // 提交评论
    submitComments() {
      if (this.comments2send.length > 0) {
        const ids = []
        let comments = []
        this.comments2send.forEach((x) => {
          comments.push(x.content)
          if (typeof x.id === 'number') {
            //  && !x.id.startsWith('myadd')
            ids.push(x.id)
          }
        })

        if (this.commentPrefix2 !== '空') {
          comments = comments.map((x) => {
            return (x = this.commentPrefix2 + x)
          })
        }
        if (!this.circleData.id) {
          this.$message.warning('没有id，不能创建！')
          return
        }
        if (!this.wechats2comment.length === 0) {
          this.$message.warning('没有设置微信，不能创建！')
          return
        }

        followMoreComment(this.circleData.id, comments, this.wechats2comment, ids)
          .then((res) => {
            if (res.code === 0) {
              this.$message.success('评论任务已经提交！')
            }
          })
          .catch((err) => {
            console.log(err)
          })
      } else {
        this.$message.warning('请先添加评论！')
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.circle-detail {
  height: 100%;
  width: 100%;
  display: flex;
  justify-content: space-between;

  h3 {
    font-size: 14px;
    font-weight: 600;
    display: flex;
    align-items: center;
    height: 42px;
    min-height: 42px;
  }

  .circle-itme {
    width: 48%;
    display: flex;
    flex-direction: column;

    .circle-content-box {
      padding: 10px;
      min-height: 20%;
      max-height: 40%;
      border: solid #f3f3f4 2px;
      border-radius: 5px;
      background-color: #f9fafc;
      overflow: auto;
      .text-content {
        line-height: 30px;
      }
      .like-list {
        display: flex;
        flex-wrap: wrap;
        align-items: center;
        color: #7485a8;
        span {
          padding: 5px 10px;
        }
      }

      .circle-content {
        flex: 1 1 auto;
        display: flex;
        flex-direction: column;
        justify-content: flex-start;
      }
    }

    .comments-box {
      flex: 1 1 auto;
      margin-bottom: 10px;
      padding: 10px;
      border: solid #f3f3f4 2px;
      border-radius: 5px;
      background-color: #f9fafc;
      display: flex;
      flex-direction: column;
      overflow: hidden;

      .comments-to-send {
        margin: 10px 0;
        flex: 1 1 auto;
        overflow: auto;

        .comment-content {
          height: 30px;
          line-height: 30px;
          background-color: #e1eefc;
          border-radius: 15px;
          margin-bottom: 10px;
          padding: 0 15px;
          position: relative;
          P {
            width: 100%;
          }
          .el-icon-delete {
            position: absolute;
            top: 7px;
            right: 7px;
            color: red;
            cursor: pointer;
          }
        }
      }

      .prefix-box {
        display: flex;
        align-items: center;
        padding: 5px 0;
      }
    }

    .submit-comment-btn {
      max-width: 300px;
      min-width: 200px;
      align-self: center;
    }
  }

  .comment-list {
    width: 48%;
    display: flex;
    flex-direction: column;

    .comment-data {
      flex: 1 1 auto;
      border: solid #efeff0 2px;
      border-radius: 5px;
      padding: 5px;
      overflow: hidden;
      background: #f9fafc;
      display: flex;
      flex-direction: column;

      .comment-ul {
        flex: 1 1 auto;
        overflow: auto;
        .comment-item {
          display: flex;
          align-items: center;
          justify-content: space-between;
          border-bottom: solid #efeff0 2px;

          .comment-item-cotent {
            display: flex;
            align-items: center;
            padding: 5px 0;
            margin-left: 10px;
          }
          .comment-item-btns {
            min-width: 200px;
            // margin-right: 10px;
          }
        }
      }
      .comment-input-area {
        &:focus {
          outline: none !important;
        }
      }

      .add-comment-btn {
        position: absolute;
        bottom: 35px;
        right: 40px;
      }
    }
  }

  #followComment2 {
    position: absolute;
    // top: 0;
    // left: 0;
    z-index: 100;
  }
  .show-model2 {
    height: 100%;
    width: 100%;
    position: absolute;
    top: 0;
    left: 0;
  }

  .follow-comment2 {
    width: 440px;
    padding: 10px;
    border: solid #e7e7e7 1px;
    border-radius: 10px;
    box-shadow: 2px 2px 2px #e7e7e7;
    position: relative;
    background: #fff;

    &::before {
      content: '';
      border: 12px solid transparent;
      border-bottom: 12px solid #e7e7e7;
      position: absolute;
      top: -24px;
      right: 20px;
    }

    &::after {
      content: '';
      border: 10px solid transparent;
      border-bottom: 10px solid #fff;
      position: absolute;
      top: -20px;
      right: 22px;
    }
  }
}
</style>
